﻿#include "tcpserver.h"
#include"QTimer"

#include <QDebug>

CTcpServer::CTcpServer(QObject *parent) : QTcpServer(parent)
{

}

void CTcpServer::incomingConnection(qintptr handle)
{
    QTcpSocket *client = new QTcpSocket();
    client->setSocketDescriptor(handle);
    connect(client, SIGNAL(disconnected()), this, SLOT(slot_disconnected()));

    connect(client, SIGNAL(readyRead()),
            this, SLOT(slot_receiveData()));

    QString ip = client->peerAddress().toString();
    int port = client->peerPort();

    emit sig_clientConnected(ip, port);
    m_clients.append(client);
}

void CTcpServer::slot_disconnected()
{

    //断开连接后从链表中移除
    QTcpSocket *client = (QTcpSocket *)sender();
    QString ip = client->peerAddress().toString();
    int port = client->peerPort();
    disconnect(client, SIGNAL(disconnected()), this, SLOT(slot_disconnected()));

    disconnect(client, SIGNAL(readyRead()),
               this, SLOT(slot_receiveData()));
    emit sig_clientDisconnected(ip, port);
    qDebug() << __FUNCTION__ <<ip << this->serverPort();
    m_clients.removeOne(client);
    //    delete client;
}

bool CTcpServer::slot_start(quint16 servPort)
{
#if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
    bool ok = listen(QHostAddress::AnyIPv4, servPort);
#else
    bool ok = listen(QHostAddress::Any, servPort);
#endif

    return ok;
}

void CTcpServer::slot_stop()
{
    foreach (QTcpSocket *client, m_clients) {
        client->disconnectFromHost();
    }

    m_clients.clear();
    this->close();
}

void CTcpServer::slot_writeData(const QString &ip,
                                int port,
                                const char *pch,
                                qint64 maxSize)
{
    foreach (QTcpSocket *client, m_clients) {
        qDebug() << __FUNCTION__ << client;
        if (client->peerAddress().toString() == ip /*&&
                        client->peerPort() == port*/) {

            client->write(pch, maxSize);
            break;
        }
    }
    port = port;        /* 去警告 */
}

void CTcpServer::slot_writeData(const char *pch, qint64 maxSize)
{
    foreach (QTcpSocket *client, m_clients) {
        client->write(pch, maxSize);
    }
}

void CTcpServer::slot_receiveData()
{
    QTcpSocket *client = (QTcpSocket *)sender();
    QByteArray data = client->readAll();
    emit sig_receiveData(data,client->peerAddress().toString(),client->peerPort());
    //    while (client->bytesAvailable()) {

    //        QByteArray data = client->readAll();
    //        emit sig_receiveData(data,client->peerAddress().toString(),client->peerPort());
    //    }
}

void CTcpServer::slot_ReadData(const QString &ip, int port, char *pch, qint64 maxSize)
{
    foreach (QTcpSocket *client, m_clients) {
        if (client->peerAddress().toString() == ip &&
                client->peerPort() == port) {

            client->read(pch, maxSize);
            break;
        }
    }
}
